import { defineStore } from "pinia";

interface PageCache {
  keys: string[];
  include: any; // 保存的数据
  max: number; // 最大缓存数
}

export const usePageCacheStore = defineStore("pageCache", {
  state: (): PageCache => {
    return {
      keys: [],
      include: {},
      max: 50,
    };
  },
  actions: {
    /**
     * @description: 添加数据
     * @param {string} key 唯一标识
     * @param {any} data
     * @param {number} expTime 过期时间（毫秒）
     * @author: zhj1214
     */
    addPageData(key: string, data: any, expTime?: number) {
      if (this.keys.length < 50) {
        if (!this.keys.includes(key)) {
          this.keys.push(key);
        }
        const time = expTime ? Date.now() + expTime : 0;
        this.include[key] = {
          expTime: time,
          data,
        };
      }
    },
    /**
     * @description: 删除数据
     * @param {string} key
     */
    removeData(key: string) {
      if (this.keys.includes(key)) {
        this.keys = this.keys.filter((e) => e !== key);
        if (this.include.hasOwnProperty(key)) {
          delete this.include[key];
        }
      }
    },
    /**
     * @description: 清空数据
     */
    cleanData() {
      this.keys = [];
      this.include = {};
    },
    /**
     * @description: 获取数据
     * @param {string} key 唯一标识
     * @return {*} 数据源
     * @author: zhj1214
     */
    getPageData(key: string) {
      if (this.include.hasOwnProperty(key)) {
        if (
          this.include[key].expTime === 0 ||
          Date.now() <= this.include[key].expTime
        ) {
          console.log("从 pageCache获取数据：", key);
          return this.include[key].data;
        } else {
          this.removeData(key);
          return false;
        }
      } else {
        return false;
      }
    },
  },
});
